<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import api from '../api';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import axios from 'axios'


const username = ref('');
const id = ref('');
const userInfo = ref({});
const imageUrl = ref('');
const editWinVisible = ref(false);
const changePasswordDialogVisible = ref(false);
const oldPassword = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const router = useRouter();



onMounted(async () => {
  try {
    const result = await api.get('/api/currentusername');
    username.value = result.data.user_name;
    id.value = result.data.id;
    const userInfoResult = await api.get(`/api/user/getusername?user_name=${username.value}`);
    userInfo.value = userInfoResult.data;
    imageUrl.value = userInfo.value.head_image 
      ? `http://localhost:8080/user/image/${userInfo.value.id}` 
      : '';
  } catch (error) {
    console.error('请求失败:', error);
  }
});

const avatarUrl = computed(() => {
  return imageUrl.value || '';
});

const handleAvatarSuccess = async (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
};

const updateInfo = async () => {
  try {
    if (userInfo.value.birthday) {
      userInfo.value.birthday = dayjs(userInfo.value.birthday).format('YYYY-MM-DDTHH:mm:ss');
    }
    await api.putJson(`/api/user/edit/${userInfo.value.id}`, userInfo.value);
    ElMessage({
      type: 'success',
      message: '信息更新成功',
    });
  } catch (error) {
    console.error('API 请求失败:', error);
    ElMessage({
      type: 'error',
      message: `更新失败: ${error.response?.data?.message || '未知错误'}`,
    });
  }
};

// const rulesRef =ref(null);
// const changePassword = async () => {
//   rulesRef.value.validate(async(valid) =>{
//     if(valid){
//       if (newPassword.value !== confirmPassword.value) {
//     ElMessage({
//       type: 'error',
//       message: '新密码和确认密码不匹配',
//     });
//     return;
//   }
//     const response = await api.putJson('/api/user/editpassword', {
//       id: userInfo.value.id,
//       oldPassword: oldPassword.value,
//       newPassword: newPassword.value,
//     });
//     if (response.code === 200) {
//       ElMessage({
//         type: 'success',
//         message: '密码修改成功,请重新登录',
//       });
//       closeChangePasswordDialog(); // 关闭对话框

//       // 直接调用登出 API 并重定向到登录页面
//       window.sessionStorage.clear();
//        window.localStorage.clear();
//       await api.post('/api/logout');
//       router.push('/login');
      
//     } else {
//       ElMessage({
//         type: 'error',
//         message: response.message || '密码修改失败',
//       });
//     }
//     }
//   } )
// };
const changePassword = async () => {
      if (newPassword.value !== confirmPassword.value) {
    ElMessage({
      type: 'error',
      message: '新密码和确认密码不匹配',
    });
    return;
  }
    const response = await api.putJson('/api/user/editpassword', {
      id: userInfo.value.id,
      oldPassword: oldPassword.value,
      newPassword: newPassword.value,
    });
    if (response.code === 200) {
      ElMessage({
        type: 'success',
        message: '密码修改成功,请重新登录',
      });
      closeChangePasswordDialog(); // 关闭对话框

      // 直接调用登出 API 并重定向到登录页面
      window.sessionStorage.clear();
       window.localStorage.clear();
      await api.post('/api/logout');
      router.push('/login');
      
    } else {
      ElMessage({
        type: 'error',
        message: response.message || '密码修改失败',
      });
    }
};


// 打开修改密码对话框
const openChangePasswordDialog = () => {
  oldPassword.value = '';
  newPassword.value = '';
  confirmPassword.value = '';
  changePasswordDialogVisible.value = true;
};

const closeChangePasswordDialog = () => {
  changePasswordDialogVisible.value = false;
};


</script>

<template>
  <div class="personal-info">
    <h2>个人信息管理</h2>
    <el-form :model="userInfo" label-width="120px">
      <el-form-item label="">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/user/image/1"
          name="head_image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <!-- 其他表单项 -->
      <el-form-item label="当前用户名">
        <el-input v-model="username" disabled></el-input>
      </el-form-item>
      <el-form-item label="真实姓名">
        <el-input v-model="userInfo.real_name" placeholder="请输入真实姓名"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="userInfo.phone" placeholder="请输入电话"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="userInfo.sex" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生日">
        <el-date-picker v-model="userInfo.birthday" type="date"></el-date-picker>
      </el-form-item>

      <!-- 按钮 -->
      <el-form-item class="form-footer">
        <div class="button-container">
          <el-button type="primary" @click="updateInfo">更新信息</el-button>
          <el-button type="warning" @click="openChangePasswordDialog">修改密码</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 修改密码的弹出框 -->
    <el-dialog
  class="update-password"
  v-model="changePasswordDialogVisible"
  title="修改密码"
  width="400px"
>
  <el-form label-width="120px" :rules="rules" ref="rulesRef" >
    <el-form-item label="原密码" prop="oldPassword" >
      <!-- :rules="[{ required: true, message: '请输入原密码', trigger: 'blur' }]" -->
      <el-input type="password" v-model="oldPassword" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword" >
      <!-- :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]" -->
      <el-input type="password" v-model="newPassword" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认新密码" prop="confirmPassword" >
      <!-- :rules="[{ required: true, message: '请输入确认新密码', trigger: 'blur' }]" -->
      <el-input type="password" v-model="confirmPassword" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <template #footer>
  <span  class="dialog-footer" >
    <el-button @click="closeChangePasswordDialog">取消</el-button>
    <el-button type="primary" @click="changePassword">保存</el-button>
  </span>
  </template>
</el-dialog>

  </div>
</template>



<style scoped>

.personal-info {
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  margin: auto;
  position: relative;
  z-index: 1;
}

.el-form-item {
  margin-bottom: 16px;
}
.dialog-footer {
  text-align: right;
}
.form-footer {
  text-align: center;
}

.el-button {
  margin: 0 10px;
}

.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}


</style>
